//
// Created by Tiany on 2021/6/21.
//

#include "LinkStack.h"
#include "stdlib.h"
#include "stdio.h"

//创建空栈
PLinkStack createEmptyStack_link(void) {
    PLinkStack pLinkStack;
    pLinkStack = malloc(sizeof(struct LinkStack));
    if (pLinkStack != NULL)
        pLinkStack->top = NULL;
    else printf("创建失败");
    return pLinkStack;
}

//判断栈是否为空
int isEmptyStack_link(PLinkStack pLinkStack) {
    return (pLinkStack->top == NULL);
}

//进栈
void push_link(PLinkStack pLinkStack, struct DataType x) {
    PNode pNode;
    pNode = malloc(sizeof(struct Node));/*因为需要插入数据，所以需要申请空间*/
    if (pNode == NULL)
        printf("进栈失败，空间申请失败");
    else {
        pNode->info = x;
        pNode->link = pLinkStack->top;/*指向原来的栈顶处*/
        pLinkStack->top = pNode;/*把栈顶指向新结点*/
    }
}

//出栈
void pop_link(PLinkStack pLinkStack) {
    PNode pNode;/*因为只是用于记录指针，所以不用申请空间*/
    if (isEmptyStack_link(pLinkStack))
        printf("空栈哦");
    else {
        pNode = pLinkStack->top;/*记录原始栈顶，用于释放内存*/
        pLinkStack->top = pLinkStack->top->link;/*栈顶指针下移*/
        free(pNode);/*释放的是指针对应的结点，即被抛出栈的结点*/
    }
}

//取栈顶元素
struct DataType top_link(PLinkStack pLinkStack) {
    if (isEmptyStack_link(pLinkStack))
        printf("空栈哦");
    else
        return (pLinkStack->top->info);

}



